#include "login_window.h"
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <iostream>
#include <QDebug>
using std::cout;
using std::endl;
bool config_server(const QStringList &list,QString *ip,int *port);
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QString ip = "";
    int port = 0;

    if(!config_server(a.arguments(),&ip,&port))
    {
        cout<<"ip or port is empty!"<<endl;
        return 0;
    }
    QString url = QString("ws://%1:%2").arg(ip).arg(port);

    LoginWindow w(nullptr,url);
    w.show();
    return a.exec();
}

bool config_server(const QStringList &commands,QString *ip,int *port)
{
    if(commands.size()>1)
    {
        //通过命令参数获取ip和端口
        int ip_index = commands.indexOf("-ip")+1;
        int port_index = commands.indexOf("-port")+1;

        if(ip_index>0&&port_index>0&&ip_index<commands.size()&&port_index<commands.size())
        {
            *ip = commands[ip_index];
            *port = commands[port_index].toInt();
            return true;
        }
    }

    QFile config_file(QCoreApplication::applicationDirPath() + "/config.json");
    if(config_file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        //通过配置json文件，获取ip和端口
        QJsonParseError err;
        auto j_doc = QJsonDocument::fromJson(config_file.readAll(),&err);
        if(err.error==QJsonParseError::NoError&&j_doc.isObject())
        {
            const QJsonObject j_obj =j_doc.object();
            auto it_server = j_obj.find("server");
            if(it_server!=j_obj.constEnd())
            {
               if(it_server->isObject())
               {
                   QJsonObject j_server = it_server->toObject();
                   auto _ip = j_server["ip"].toString("");
                   auto _port = j_server["port"].toInt(0);
                   if(_ip.size()>0&&_port>0)
                   {
                       *ip = _ip;
                       *port = _port;
                       return true;
                   }
               }
            }
        }
    }

    return false;
}
